package gold.digger;

import gold.utils.InputUtil;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LCJZOF040 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int maximalRectangle(String[] matrix) {
            if (matrix.length <= 0) return 0;
            int maxArea = 0;
            int[] rowHeight = new int[matrix[0].length()];
            for (int i = 0; i < matrix.length; i++) {
                for (int j = 0; j < matrix[0].length(); j++) {
                    if (matrix[i].charAt(j) == '0') rowHeight[j] = 0;
                    else rowHeight[j]++;
                }

                int curArea = getMaximumRectangleAreaForHistogram(rowHeight);
                maxArea = Math.max(maxArea, curArea);
            }

            return maxArea;
        }

        public int getMaximumRectangleAreaForHistogram(int[] heights) {
            Stack<Integer> incStack = new Stack<>(); // incStack 存储 递增的 下标
            incStack.push(-1);
            int maxArea = 0;

            for (int i = 0; i <= heights.length; i++) {
                int height1 = i == heights.length ? -1 : heights[i];
                while (incStack.peek() != -1 && height1 < heights[incStack.peek()]) {
                    int height = heights[incStack.pop()];
                    int curArea = height * (i - incStack.peek() - 1);
                    maxArea = Math.max(maxArea, curArea);
                }

                incStack.push(i);
            }

            return maxArea;
        }
    }

    public void run() {
        System.out.println(new Solution().getMaximumRectangleAreaForHistogram(InputUtil.toIntegerArray("[2,1,5,6,2,3]")));
        System.out.println(new Solution().getMaximumRectangleAreaForHistogram(InputUtil.toIntegerArray("[2,4]")));
        System.out.println(new Solution().maximalRectangle(new String[]{"10100", "10111", "11111", "10010"}));
        System.out.println(new Solution().maximalRectangle(new String[]{}));
        System.out.println(new Solution().maximalRectangle(new String[]{"0"}));
        System.out.println(new Solution().maximalRectangle(new String[]{"1"}));
        System.out.println(new Solution().maximalRectangle(new String[]{"00"}));
    }

    public static void main(String[] args) throws Exception {
        LCJZOF040 an = new LCJZOF040();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
